#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <unistd.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>

#define PORT 5000
#define MAXDATASIZE 1024
#define BACKLOG 1

int main()
{
    char recvbuf[MAXDATASIZE];
    char sendbuf[MAXDATASIZE];
    int sockfd, connectfd;

    struct sockaddr_in server; //server's address information
    struct sockaddr_in client;  // client's address information

    socklen_t addrlen;

    /*create tcp socket*/
    if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
    {
        printf("create socket failed\n");
        exit(1);
    }

    //set socket options
    int opt = SO_REUSEADDR;
    setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));

    bzero(&server, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(PORT);
    server.sin_addr.s_addr = htonl(INADDR_ANY);

    //bind socket
    if(bind(sockfd, (struct sockaddr *)&server, sizeof(server)) == -1)
    {
        printf("bind error\n");
        exit(1);
    }

    //listen scoket
    if(listen(sockfd, BACKLOG) == -1) // XXX
    {
        printf("listen error\n");
        exit(1);
    }

    addrlen = sizeof(client);

    while(1)
    {
        //conncet the socket
        if((connectfd = accept(sockfd, (struct sockaddr *)&client, &addrlen)) == -1)
        {
            printf("accept error\n");
            exit(1);
        }

        struct timeval tv;
        gettimeofday(&tv, NULL);
        printf("client's ip %s, port %d at time %ld.%ld\n", \
                inet_ntoa(client.sin_addr), htons(client.sin_port), tv.tv_sec, tv.tv_usec);

        int ret = -1;
        while(1)
        {
            bzero(recvbuf, sizeof(recvbuf));
            ret = recv(connectfd, recvbuf, MAXDATASIZE, 0);
            if(ret > 0)
            {
                printf("%s\n", recvbuf);
            }
            else
            {
                close(connectfd);
                break;
            }

            ret = send(connectfd, recvbuf, ret, 0);

            if (ret > 0) {
            }
            else {
                close(connectfd);
                break;
            }
        }       
    }

    close(sockfd);

    return 0;
}

